import axios, {
    AxiosInstance,
    AxiosRequestConfig,
    AxiosResponse,
    InternalAxiosRequestConfig
  } from 'axios'
  
  
  // 定义接口返回的数据结构（根据实际项目调整）
  interface ApiResponse<T = any> {
    code: number
    msg: string
    data: T
  }
  
  // 创建自定义配置的axios实例
  class Http {
    private instance: AxiosInstance
    private readonly baseURL: string
  
    constructor() {
      this.baseURL = import.meta.env.VITE_API_BASE_URL as string || '/api'   //请求url根路径
      this.instance = axios.create({
        baseURL: this.baseURL,
        timeout: 10000,
        headers: { 'Content-Type': 'application/json' }
      })
  
      // 请求拦截器
      this.instance.interceptors.request.use(
        (config: InternalAxiosRequestConfig) => {
          // 添加认证token
          const token = localStorage.getItem('token')
          if (token) {
            // config.headers.Authorization = `Bearer ${token}`
            config.headers.Authorization = token
          }
          return config
        },
        (error: any) => Promise.reject(error)
      )
  
      // 响应拦截器
      this.instance.interceptors.response.use(
        (response: AxiosResponse) => {
          // 直接返回业务数据
          if(response.data.code === 10000){
            return response.data
          }
          else{

            let message = response.data.msg || '请求失败';

             //使用 element-ui的message组件 提示错误信息
            return Promise.reject(message);

          }
     
        },
        (error: any) => {
          // 统一错误处理
          return this.handleError(error)
        }
      )
    }
  
    // 处理响应错误
    private handleError(error: any): Promise<never> {
      let errorMessage = '请求失败'
  
      if (error.response) {
        // 服务器返回错误状态码
        switch (error.response.status) {
          case 401:
            errorMessage = '未授权，请重新登录'
            // 跳转到登录页
            break
          case 403:
            errorMessage = '拒绝访问'
            break
          case 404:
            errorMessage = '请求资源不存在'
            break
          case 500:
            errorMessage = '服务器错误'
            break
          default:
            errorMessage = `服务器响应异常 [${error.response.status}]`
        }
      } else if (error.request) {
        // 请求已发出但无响应
        errorMessage = '网络连接异常，请检查网络'
      } else {
        // 请求配置问题
        errorMessage = error.message
      }
  
      // 实际项目中可使用UI库的提示组件
      console.error('请求错误:', errorMessage)
      return Promise.reject(new Error(errorMessage))
    }
  
    // 封装请求方法
    public request<T = any>(config: AxiosRequestConfig): Promise<ApiResponse<T>> {
      return this.instance.request(config)
    }
  
    public get<T = any>(
      url: string,
      params?: object,
      config?: AxiosRequestConfig
    ): Promise<ApiResponse<T>> {
      return this.request({ method: 'GET', url, params, ...config })
    }
  
    public post<T = any>(
      url: string,
      data?: object,
      config?: AxiosRequestConfig
    ): Promise<ApiResponse<T>> {
      return this.request({ method: 'POST', url, data, ...config })
    }
  
    public put<T = any>(
      url: string,
      data?: object,
      config?: AxiosRequestConfig
    ): Promise<ApiResponse<T>> {
      return this.request({ method: 'PUT', url, data, ...config })
    }
  
    public delete<T = any>(
      url: string,
      params?: object,
      config?: AxiosRequestConfig
    ): Promise<ApiResponse<T>> {
      return this.request({ method: 'DELETE', url, params, ...config })
    }
  }
  
  const http = new Http()
  export default http